import { error } from '../../../output.js'
import { getVariable } from '../../../tools/variable.js'
import call_run from './call.js'

const run = async (runtime, ast, node) => {
  if (node.type !== 'ReturnStatement') return

  if (node.argument === null) {
    runtime.return = undefined
    return
  }

  if (node.argument.type === 'Literal') {
    runtime.return = node.argument.value
  } else if (node.argument.type === 'Identifier') {
    const value = getVariable(runtime, node.argument.name, ast.filepath)
    if (value !== null) {
      runtime.return = value
    } else {
      error(`Variable not found: ${ node.argument.name }`)
    }
  } else if (node.argument.type === 'CallExpression') {
    runtime.return = await call_run(runtime, ast, node.argument)
  } else {
    error(`Unsupported return value type: ${ node.argument.type }`)
  }
}

export default run